import CommandType = xpTerminal.CommandType;
import ComponentOutputType = xpTerminal.ComponentOutputType;
import { defineAsyncComponent } from 'vue';
import { commandMap } from './commandRegister';
/**
 * 百度搜索命令
 */
const baiduCommand: CommandType = {
    func: 'baidu',
    name: '百度搜索',
    alias: ['bd'],
    desc: '百度搜索',
    params: [
        {
            key: 'word',
            desc: '搜索内容',
            required: true
        }
    ],
    options: [
        {
            key: 'self',
            desc: '是否当前页面打开',
            alias: ['s'],
            type: 'boolean',
            defaultValue: false
        },
        {
            key: 'picture',
            desc: '是否搜索图片',
            alias: ['p'],
            type: 'boolean',
            defaultValue: false
        },
        {
            key: 'wenku',
            desc: '是否搜索百度文库',
            alias: ['w'],
            type: 'boolean',
            defaultValue: false
        }
    ],
    action (options, terminal) 
    {
        const { _, self, picture, wenku } = options;
        const word = _.length > 0 ? _[0] : '';
        let targetLink = `https://www.baidu.com/s?wd=${word}`;
        // 搜索图片
        if (picture) 
        {
            targetLink = `https://image.baidu.com/search/index?tn=baiduimage&word=${word}`;
        }
        else if (wenku)
        {
            targetLink = `https://wenku.baidu.com/search?word=${word}`;
        }
        if (self) 
        {
            window.location.href = targetLink;
        } 
        else 
        {
            window.open(targetLink, '_blank');
        }
    }
};

/**
 * 音乐搜索命令
 */
const musicCommand: CommandType = {
    func: 'music',
    name: '音乐搜索',
    alias: ['bgm'],
    desc: '音乐搜索',
    params: [
        {
            key: 'word',
            desc: '搜索内容',
            required: true
        }
    ],
    options: [
        {
            key: 'address',
            desc: '搜索平台地址[网易云：wyy, QQ音乐：qq, 酷狗音乐：kg]',
            alias: ['a'],
            type: 'string',
            defaultValue: 'wyy'
        }
    ],
    action (options, terminal) 
    {
        let { _, address } = options;
        if (!address) address = 'wyy';
        const word = _.length > 0 ? _[0] : '';
        let musicLink = {
            wyy:'https://music.163.com/#/search/m/?s=',
            qq:'https://y.qq.com/n/ryqq/search?w=',
            kg:'https://www.kugou.com/yy/html/search.html#searchType=song&searchKeyWord='
        };
        let targetLink = musicLink[address] + word;
        window.open(targetLink, '_blank');
    }
};


/**
 * ping命令
 */
const pingCommand: CommandType = {
    func: 'ping',
    name: 'ping',
    desc: '检测网络地址的连通情况',
    params: [
        {
            key: 'link',
            desc: '目标地址',
            required: true
        }
    ],
    options: [
        {
            key: 'timeout',
            desc: '请求超时时间(单位:毫秒)',
            alias: ['t'],
            type: 'string',
            defaultValue: '3000'
        }
    ],
    async action (options, terminal) 
    {
        const { _ } = options;
        const { timeout = '3000' } = options;
        if (_.length < 1) 
        {
            terminal.writeTextErrorResult('参数不足');
            return;
        }
        let dest = _[0];
        if (
            !dest.toLowerCase().startsWith('http://') &&
            !dest.toLowerCase().startsWith('https://')
        ) 
        {
            dest = 'https://' + dest;
        }
        if (dest.toLowerCase().startsWith('http://')) 
        {
            dest = dest.replace('http://', 'https://');
        }
        const startTime = new Date().getTime();
        const res = await Promise.race([
            new Promise(function (resolve, reject) 
            {
                setTimeout(() => reject(new Error('ping请求超时')), Number(timeout));
            }),
            fetch(dest, { mode: 'no-cors', cache: 'reload' })
        ])
            .then((resp: any) => 
            {
                if (resp.ok || resp.status === 200 || resp.type === 'opaque') 
                {
                    console.log(resp);
                    const finishTime = new Date().getTime();
                    terminal.writeTextSuccessResult(`目标地址正常 延迟=${(finishTime - startTime).toString()}ms`);
                } 
                else 
                {
                    terminal.writeTextErrorResult(`"${_[0]}" 地址 ping 不通`);
                }
            })
            .catch((error) => 
            {
                console.log(error);
                terminal.writeTextErrorResult(`ping 请求找不到地址 "${_[0]}" 请检查该名称，然后重试`);
            });
    }
};

/**
 * 清除命令
 */
const clearCommand: CommandType = {
    func: 'clear',
    name: '清屏',
    alias: ['cl', 'clr'],
    desc: '清屏',
    params: [],
    options: [],
    action (options, terminal) 
    {
        setTimeout(() => 
        {
            terminal.clear();
        }, 100);
    }
};

/**
 * 帮助命令
 */
const helpCommand: CommandType = {
    func: 'help',
    name: '帮助',
    desc: '命令帮助',
    alias: ['xp'],
    params: [
        {
            key: 'commandName',
            desc: '命令英文名称'
        }
    ],
    options: [],
    action (options, terminal) 
    {
        const { _ } = options;
        if (_.length < 1)
        {
            // 输出所有命令
            const output: ComponentOutputType = {
                type: 'component',
                component: defineAsyncComponent(() => import('./help/HelpBox.vue'))
            };
            terminal.writeResult(output);
            return;
        }
        // 输出某个命令的帮助
        const commandName = _[0];
        let commands = commandMap;
        const command = commands[commandName];
        if (!command) 
        {
            terminal.writeTextErrorResult('找不到指定命令');
            return;
        }
        const output: ComponentOutputType = {
            type: 'component',
            component: defineAsyncComponent(() => import('./help/CommandHelpBox.vue')),
            props: {
                command
            }
        };
        terminal.writeResult(output);
    }
};

export default [
    helpCommand,
    pingCommand,
    clearCommand,
    baiduCommand,
    musicCommand
];

